package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import persistence.CustomerDao;

/**
 * Servlet implementation class SetCollect
 */
@WebServlet("/SetCollect")
public class SetCollect extends MyHttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}
	
	//TODO Connect the Database
	private void process(HttpServletRequest request,
			HttpServletResponse response) {
		Document xmlDoc = getDocument(request);
		NodeList user = xmlDoc.getElementsByTagName("collect").item(0).getChildNodes();
		String username =  user.item(0).getFirstChild().getNodeValue();
		long id =  Long.parseLong((String)user.item(1).getFirstChild().getNodeValue());
		boolean isCollect = ((String)user.item(2).getFirstChild().getNodeValue()).equals("yes") ? true : false;

		if (isCollect) {
			CustomerDao.modifyFavorite(CustomerDao.nameToID(username), id);
		} else {		
			CustomerDao.deleteFavorite(CustomerDao.nameToID(username), id);
		}
	}

}
